#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef _WIN64
    #define USE_SCANF
#else
    #ifdef _WIN32
        #define USE_SCANF
    #else
        #define USE_ARGV
    #endif

#endif

void get_now_time(const char *start_string)
{
	time_t tmpcal_ptr;
	struct tm *tmp_ptr = NULL;

	time(&tmpcal_ptr);
	tmp_ptr = localtime(&tmpcal_ptr);

	printf ("%s\t%04d-%02d-%02d\t%02d:%02d:%02d\n",start_string,(1900+tmp_ptr->tm_year), (1+tmp_ptr->tm_mon), tmp_ptr->tm_mday, tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);
}

int make_number(int count,int *p)
{
	unsigned char exit_flag = 0;
	unsigned int value;
	int *number = NULL;
	int i = 0;
	int j = 0;
	unsigned char continue_flag = 0;
	unsigned long counter = 0;

	number = malloc(count*sizeof(int));
	if(number == NULL)
	{
		return -1;
	}

	//memset(number,count+1,count*sizeof(int));
	for(j = 0;j<count;j++)
	{
		*(number+j) = count + 1;
	}

	do
	{
		#ifdef USE_ARGV
		value = rand() % 0x7fff;
		#else
		value = rand();
		#endif
		counter++;
		if(value > 0 && value <= count)
		{
			for(j = 0;j < count;j++)
			{
				if(*(number+j) == value && *(number+j) != count + 1)
				{
					continue_flag = 1;
					break;
				}
			}

			if(continue_flag)
			{
				continue_flag = 0;
				continue;
			}

			{
				*(number+i) = value;
				printf("[%d] get number %d\tuse\t%ld \n",i+1,*(number+i),counter);
				i++;
				counter = 0;
			}
		}
		
		if(i >= count)
		{
			exit_flag = 1;
		}

	}while(!exit_flag);

	printf("\n\n");
	//打印
	#if 0
	for(k = 0;k < count;k++)
	{
		printf("[%d] %d\n",k,*(number+k));
	}
	#endif

	memcpy(p,number,count*sizeof(int));

	free(number);
	number = NULL;
	return 0;
}

int main(int argc, char **argv)
{
	int *number = NULL;
	int max_value = 20;
	int k = 0;
	unsigned char continue_flag = 0;
	unsigned long counter = 0;

	#ifdef USE_SCANF
	printf("This is Windows OS\n");
    printf("Pls input max value RAND_MAX %d\n",RAND_MAX);
    scanf("%d",&max_value);
	#endif // USE_SCANF

	#ifdef USE_ARGV
	if(argc > 1)
	{
	    printf("This is Linux OS\n");
    	max_value = atoi(argv[1]);
	}
    #endif

	printf("max_value = %d\n",max_value);

	number = malloc(max_value*sizeof(int));
	if(number == NULL)
	{
		return -1;
	}
	memset(number,0,max_value*sizeof(int));


	get_now_time("start");

	srand((unsigned)time(NULL));
	do
	{
		make_number(max_value,number);
		counter++;
		for(k = 0;k < max_value;k++)
		{
			if(k+1 != *(number+k))
			{
				continue_flag = 1;
				k = 0;
				break;
			}
		}

		if(continue_flag)
		{
			continue_flag = 0;
			continue;
		}

		if(k >= max_value)
		{
			printf("Done Check %ld times\n",counter);
			break;
		}
	}
	while(1);
	get_now_time("end");

	#ifdef USE_SCANF
	do
    {
          sleep(10);
    }while(1);
    #endif

    return 0;
}

